package com.yskj.mwk.utils;

import com.yskj.mwk.bean.Goods;
import com.yskj.mwk.bean.Order;
import com.yskj.mwk.bean.OrderDesc;
import com.yskj.mwk.dao.ManagerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@Component
public class PdfCover {

    private final ManagerMapper managerMapper;

    @Autowired // 构造器注入
    public PdfCover(ManagerMapper managerMapper) {
        this.managerMapper = managerMapper;
    }

    /**
     * 生成pdf封面图片
     * @param templatePath 模板背景图路径（需包含绿色渐变背景）
     * @param outputPath   输出图片路径
     * @param qrCodePath   二维码图片路径
     * @param userInfo     用户信息对象
     */
    public void generateCard(String templatePath, String outputPath,
                             String qrCodePath, UserInfo userInfo,String pdfFirstPic,String pdfLastPic) throws IOException {
        System.out.println(templatePath);
        // 加载模板背景图
        URL url = new URL(templatePath);
        BufferedImage template = ImageIO.read(url);
        int width = template.getWidth();  // 假设模板宽度800px
        int height = template.getHeight(); // 假设模板高度600px

        Graphics2D g = template.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 设置统一字体样式
        Font titleFont = new Font("微软雅黑", Font.BOLD, 32);
        Font detailFont = new Font("微软雅黑", Font.PLAIN, 28);
        g.setColor(Color.BLACK); // 所有文字为黑色

        // 绘制个人信息（网页顶部）
        g.setFont(titleFont);
        g.drawString(userInfo.getName(), 60, 80);         // 姓名
        g.drawString(userInfo.getPhone(), 60, 130);       // 电话

        // 绘制地址（分两行）
        g.setFont(detailFont);
        String[] addressLines = userInfo.getAddress().split("\n");
        g.drawString(addressLines[0], 60, 200);  // 第一行地址
        g.drawString(addressLines[1], 60, 240);  // 第二行地址

        // 绘制产品信息（重复两次）
        int productY = 300;
        for (int i = 0; i < 2; i++) {
            g.drawString(userInfo.getProduct(), 60, productY);
            productY += 40; // 行间距
        }

        // 添加二维码（右侧布局）
        BufferedImage qrCode = ImageIO.read(new File(qrCodePath));
        int qrWidth = 200; // 二维码显示尺寸
        int qrX = width - qrWidth - 50; // 右侧留白50px
        int qrY = 380; // 与产品信息对齐
        g.drawImage(qrCode, qrX, qrY, qrWidth, qrWidth, null);

        // 添加产品图片1
        URL urlz = new URL(pdfFirstPic);
        BufferedImage picz = ImageIO.read(urlz);
        int piczoriginWidth = picz.getWidth();
        int piczoriginHeight = picz.getHeight();
        int piczWidth = 100; // 二维码显示尺寸
        double aspectRatio = (double) piczoriginHeight / piczoriginWidth; // 计算宽高比[9,11](@ref)
        int piczHeight = (int) (piczWidth * aspectRatio);
        int piczX = 50; // 右侧留白50px
        int piczY = 380; // 与产品信息对齐
        g.drawImage(picz, piczX, piczY, piczWidth, piczHeight, null);

        // 添加产品图片2
        URL urlf = new URL(pdfLastPic);
        BufferedImage picf = ImageIO.read(urlf);
        int picforiginWidth = picf.getWidth();
        int picforiginHeight = picf.getHeight();
        int picfWidth = 100; // 二维码显示尺寸
        double aspectRatio2 = (double) picforiginHeight / picforiginWidth; // 计算宽高比[9,11](@ref)
        int picfHeight = (int) (picfWidth * aspectRatio2);
        int picfX = 170; // 右侧留白50px
        int picfY = 380; // 与产品信息对齐
        g.drawImage(picf, picfX, picfY, picfWidth, picfHeight, null);

        // 底部信息
        g.setFont(new Font("宋体", Font.PLAIN, 20));
        g.drawString("Page: " + userInfo.getPageNum(), qrX, qrY + qrWidth + 30);
        g.drawString(userInfo.getProductionCode(), qrX, qrY + qrWidth + 60);
        g.drawString("（生产码，勿扫）", qrX, qrY + qrWidth + 90);

        g.dispose();

        // 输出图片
        ImageIO.write(template, "PNG", new File(outputPath));
    }

    // 用户信息实体类
    public static class UserInfo {
        private String name;
        private String phone;
        private String address; // 包含换行符的地址
        private String product;
        private String pageNum;
        private String productionCode;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getProduct() {
            return product;
        }

        public void setProduct(String product) {
            this.product = product;
        }

        public String getPageNum() {
            return pageNum;
        }

        public void setPageNum(String pageNum) {
            this.pageNum = pageNum;
        }

        public String getProductionCode() {
            return productionCode;
        }

        public void setProductionCode(String productionCode) {
            this.productionCode = productionCode;
        }
    }

    public String getCover(String orderId,int oid,String templatePath,String qrCodePath,String pdfFirstPic,String pdfLastPic){
        Order order=managerMapper.getOrderById(orderId);
        OrderDesc orderDesc=managerMapper.getOrderDesc(oid);
        Goods goods=managerMapper.getGoodsSpu(orderDesc.getSpuId());
        int num=managerMapper.getPdfNum(oid);
        if (goods.getIsTwo()==2){
            num=num*2;
        }
        num=num+2;
        UserInfo user = new UserInfo();
        user.setName(order.getReceiveName());
        user.setPhone(order.getReceiveTell());
        user.setAddress(order.getProv()+order.getCity()+order.getArea()+"\n"+order.getXx());
        user.setProduct(orderDesc.getGoodsSpec());
        user.setPageNum("P"+num);
        user.setProductionCode(orderId+"_"+oid);
        String fileName = UUID.randomUUID().toString() + ".png";
        //3.1 判断文件夹是否存在，不存在则创建
        String imageDirPath = "./upload/pdfcover";
        File imageDir = new File(imageDirPath);
        if (!imageDir.exists()) {
            imageDir.mkdirs();
        }

        //3.2 拼接文件完整路径
        String outputPath = imageDirPath + "/" + fileName;
        try {
            generateCard(templatePath,outputPath,qrCodePath,user , pdfFirstPic, pdfLastPic);
        }catch (Exception e){
            e.printStackTrace();
        }
        return outputPath;
    }
//    // 使用示例
//    public static void main(String[] args) throws IOException {
//        UserInfo user = new UserInfo();
//        user.setName("Angela");
//        user.setPhone("19864866406");
//        user.setAddress("广东省 深圳市龙岗区\n麓园一期三栋b座504号");
//        user.setProduct("全切贴纸-亮膜-4cm");
//        user.setPageNum("P21");
//        user.setProductionCode("202502252303161550021");
//
//        new PdfCover().generateCard(
//                "E:\\ideaWorkSpace\\mwk_admin\\upload\\image\\avatar\\2025\\02\\14/pdf_z.png",
//                "./upload/pdfs/out.png",
//                "E:\\ideaWorkSpace\\mwk_admin\\upload\\image\\avatar\\2025\\02\\14/123.png",
//                user
//        );
//    }

}
